import json
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from ..forms import TaskModelForm
from .. import models
from ..utils.pagination import Pagination


def task_list(request):
    queryset = models.Task.objects.all().order_by("level")
    form = TaskModelForm()

    page_object = Pagination(request, queryset)
    context = {
        "form": form,
        "queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, "app_02/task_list.html", context)


@csrf_exempt
def task_ajax(request):
    print(request.GET)
    print(request.POST)
    data_dict = {"status": True, "data": [11, 22, 33, 55]}
    json_string = json.dumps(data_dict)
    return HttpResponse(json_string)


@csrf_exempt
def task_add(request):
    print(request.POST)

    form = TaskModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        data_dict = {"status": True}
        json_string = json.dumps(data_dict)
        return HttpResponse(json_string)

    data_dict = {"status": False, "error": form.errors}
    return HttpResponse(json.dumps(data_dict, ensure_ascii=False))
